const onlineUsers = { count: 0 }
const visitLogService = require('../services/visitLogService')
const articleLogService = require('../services/articleLogService')

function judgeTerminalBrowser (userAgent) {
    let data = {
        client: undefined,
        browser: undefined
    };
    let regs = {};
    let client = {
        'windows nt 10': 'Windows 10',
        'windows nt 6.3': 'Windows 8.1',
        'windows nt 6.2': 'Windows 8',
        'windows nt 6.1': 'Windows 7',
        'windows nt 6.0': 'Windows Vista',
        'windows nt 5.2': 'Windows Server 2003XP x64',
        'windows nt 5.1': 'Windows XP',
        'windows xp': 'Windows XP',
        'windows nt 5.0': 'Windows 2000',
        'windows me': 'Windows ME',
        'win98': 'Windows 98',
        'win95': 'Windows 95',
        'win16': 'Windows 3.11',
        'macintosh|mac os x': 'Mac OS X',
        'mac_powerpc': 'Mac OS 9',
        'linux': 'Linux',
        'ubuntu': 'Ubuntu',
        'phone': 'iPhone',
        'pod': 'iPod',
        'pad': 'iPad',
        'android': 'Android',
        'blackberry': 'BlackBerry',
        'webos': 'Mobile',
        'freebsd': 'FreeBSD',
        'sunos': 'Solaris'
    };

    for (let key in client) {
        if (new RegExp(key).test(userAgent.toLowerCase())) {
            data.client = client[key];
            break;
        }
    }

    if (regs = userAgent.match(/MSIE\s(\d+)\..*/)) {
        // ie 除11
        data.browser = 'ie ' + regs['1'];
    } else if (regs = userAgent.match(/FireFox\/(\d+)\..*/)) {
        data.browser = 'firefox ' + regs['1'];
    } else if (regs = userAgent.match(/Opera[\s|\/](\d+)\..*/)) {
        data.browser = 'opera ' + regs['1'];
    } else if (regs = userAgent.match(/Chrome\/(\d+)\..*/)) {
        data.browser = 'chrome ' + regs['1'];
    } else if (regs = userAgent.match(/Safari\/(\d+)\..*$/)) {
        // chrome浏览器都声明了safari
        data.browser = 'safari ' + regs['1'];
    } else if (regs = userAgent.match(/rv:(\d+)\..*/)) {
        // ie 11
        data.browser = 'ie ' + regs['1'];
    }
    return data;
}

function getTimeStamp (time) {
    return new Date(time || Date.now()).getTime();
}

function getClientInfo (socket) {
    let client = judgeTerminalBrowser(socket.handshake.headers['user-agent'])
    let ip = ''
    if (socket.handshake.headers['x-forwarded-for'] != null) {
        ip = socket.handshake.headers['x-forwarded-for'];
    } else {
        ip = socket.handshake.address;
    }
    client.ip = ip
    return client
}

const supervise = {
    run (server) {
        const io = require('socket.io')(server, { path: '/supervise' });
        io.on('connection', (socket) => {
            onlineUsers.count = onlineUsers.count + 1
            socket.emit('onlineUser', onlineUsers.count)


            // 某个用户连接 发送自己的用户信息
            socket.on('userConnect', (data) => {
                onlineUsers[socket.id] = data
                // console.log(onlineUsers)
                // 返回用户上线的信息
                socket.emit('oneUserIn', onlineUsers.count)
                visitLogService.insertOneLog({
                    userId: data.id,
                    userName: data.name,
                    status: 'start',
                    action: 'visit',
                    target: 'vv',
                    ts: getTimeStamp(),
                    client: getClientInfo(socket)
                }).then(res => {
                    console.log('insertOneLog', res)
                }).catch(err => {
                    console.log(err)
                })
            });

            // 接收到客户端发来的消息
            socket.on('clientMsg', (data) => {
                // 文章记录
                if (data.target === 'article') {
                    data.ts = getTimeStamp()
                    data.client = getClientInfo(socket)
                    articleLogService.insertOneLog(data).then(res => {
                        console.log('articleLog', res)
                    }).catch(err => {
                        console.log(err)
                    })
                }
            });

            // 某个客户端断开了连接
            socket.on('disconnect', (reason) => {
                console.log('user disconnected', reason, socket.id);
                delete onlineUsers[socket.id]
                onlineUsers.count = onlineUsers.count - 1
                // 给所有用户发送断开的消息
                io.emit('oneUserOut', onlineUsers.count)
            });
        });
    }
}
module.exports = supervise

